package com.kanas.webak.admin.service;

import javax.inject.Singleton;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kanas.app.web.security.PrincipalDetails;
import com.kanas.framework.support.LoggerSupport;
import com.kanas.webak.admin.repository.UserRepository;

@Service("kanas.admin.service.userdetails")
@Singleton
public class SecurityUserDetailsImpl extends LoggerSupport implements UserDetailsService {

	@Autowired
	private UserRepository userRepository;
			
	public UserRepository getUserRepository() {
		return userRepository;
	}

	public void setUserRepository(UserRepository userRepository) {
		this.userRepository = userRepository;
	}

	@Override
	@Transactional
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		this.logDebug("load user:",username);
		PrincipalDetails sysUser = this.userRepository.findByUsername(username);
		if(sysUser==null){
			this.logDebug("not user found.");
			return null;
		}
		sysUser.getAuthorities().size(); //force to fetch roles immediately
		return sysUser;
	}

}